/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package counter.stosc.com;

import java.io.*;
import javax.microedition.rms.*;

/**
 *
 * @author Stosc
 */
public class Model {

    private RecordStore counterStore = null;
    public static final String RNAME = "counter";

    /**
     * 内部类，通过实现RecordComparator接口来实现记录按日期排序
     */
    private class DateComparator implements RecordComparator{
        public int compare(byte[] data1,byte[] data2){
            try{
            int i = byteArrayToCounter(data1).compareTo(byteArrayToCounter(data2));
            if(i < 0){
                return RecordComparator.FOLLOWS;
            }else if(i == 0){
                return RecordComparator.EQUIVALENT;
            }else if(i > 0){
                return RecordComparator.PRECEDES;
            }
            return i;
            }catch(IOException e){
               return 0;
            }
        }
    }

    public Model(){
        try{
           counterStore = RecordStore.openRecordStore(RNAME, true);
        }catch (RecordStoreException e){
            e.printStackTrace();
        }
    }

     public void closeRecordStore(){
        try{
            counterStore.closeRecordStore();
        }catch(RecordStoreException e){
            e.printStackTrace();
        }
     }

    public boolean addCounter(Counter counter){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        ByteArrayOutputStream newBaos = new ByteArrayOutputStream();
        DataOutputStream newDos = new DataOutputStream(newBaos);
        try {
//            counter.setId(counterStore.getNumRecords() + 1);
            counter.serialize(dos);
            byte[] data = baos.toByteArray();
            int recID = counterStore.addRecord(data, 0, data.length);
            counter.setId(recID);
            counter.serialize(newDos);
            byte[] newData = newBaos.toByteArray();
            counterStore.setRecord(recID, newData, 0, newData.length);
            dos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (RecordStoreException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public Counter getCounter(int index){
        try {
            if (counterStore.getNumRecords() > 0) {
                byte[] data = counterStore.getRecord(index);
                Counter counter = byteArrayToCounter(data);
                return counter;
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (RecordStoreException e) {
            e.printStackTrace();
            return null;
        }
    }

    public boolean updateCounter(Counter counter){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        try {
            counter.serialize(dos);
            byte[] data = baos.toByteArray();            
            counterStore.setRecord(counter.getId(),data, 0, data.length);
            dos.close();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (RecordStoreException e) {
            e.printStackTrace();
            return false;
        }finally{
            if(dos != null){
                dos = null;
            }
        }
        return true;
    }

    public boolean removeCounter(Counter counter){
        try {
            counterStore.deleteRecord(counter.getId());
        } catch (RecordStoreException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public Counter[] getAll(){
        try{
            //这里返回的记录是符合SearchComparator的排列顺序并经过SearchFilter筛选的记录
            RecordEnumeration re = counterStore.enumerateRecords(null, new DateComparator(), false);
            if(re.numRecords() <= 0){
                return null;
            }else{
                Counter[] counter = new Counter[re.numRecords()];
                int i = 0;
                while(re.hasNextElement()){
                    counter[i++]  = byteArrayToCounter(re.nextRecord());
                }
                return counter;
            }

        }catch(RecordStoreException e){
            e.printStackTrace();
            return null;
        }catch(NullPointerException e){
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            return null;
        }

    }

    private Counter byteArrayToCounter(byte[] data) throws IOException {
       ByteArrayInputStream bais = new ByteArrayInputStream(data);
       DataInputStream dis = new DataInputStream(bais);
        try{
            Counter counter = Counter.deserialize(dis);
            dis.close();
            bais.close();
            return counter;
         } catch (IOException e) {
            e.printStackTrace();
            return null;
         }finally{
            if(dis != null){
                dis = null;
            }
            if(bais != null){
                bais = null;
            }
         }
    }

}
